package test01;

import java.util.Scanner;

public class Test_1076 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while (t-- > 0) {
            int year = sc.nextInt();
            int n = sc.nextInt();
            while (!((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)) {
                year++;
            }
            int count = 0;
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                for (; ; year += 4) {
                    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                        count++;
                    }
                    if (count == n) {
                        System.out.println(year);
                        break;
                    }
                }
            }
        }
    }
}
